package insertdeleteupdate;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
    public Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql://60.205.142.63/how2j?characterEncoding=UTF-8", "root", "root");
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void insertTest() {

        String sql = "insert into hero (name,hp,damage) values('拉莫斯',1200,15)";
        try (
                Connection connection = getConnection();
                Statement statement = connection.createStatement();
        ) {
            statement.execute(sql);
            System.out.println("执行成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void deleteTest() {
        String sql = "delete from hero where id >10";
        try (
                Connection connection = getConnection();
                Statement statement = connection.createStatement()
        ) {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void updateTest() {
        String sql = "update hero set name = '德玛西亚之力', hp=1000,damage=8 where id=10";
        try (
                Connection connection = getConnection();
                Statement statement = connection.createStatement()
        ) {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设计一个方法：方法接受的参数是SQL语句，无论是增加、删除、还是修改，都调用这个方法，每次传不同的SQL语句作为参数
     *
     * @param sql
     */
    public static void execute(String sql) {
        //1. 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try (
                Connection connection = DriverManager.getConnection("jdbc:mysql://60.205.142.63:3306/how2j?characterEncoding=UTF-8", "root", "root");
                Statement statement = connection.createStatement();) {
            statement.execute(sql);
            System.out.println("sql执行完毕");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void executeTest() {
//        String sql1 = "insert into hero (name,hp,damage) values('拉莫斯',1200,15)";
        String sql2 = "delete from hero where id >10";
//        String sql3 = "update hero set name = '荣耀行刑官', hp=1001,damage=10 where id=1003";
//        execute(sql1);
//        execute(sql3);
        execute(sql2);
    }

}
